package na.learn.java.serialization;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Calendar;
import java.util.GregorianCalendar;


/**
 * Notice the diff in seconds of persisted object and the one retrieved.
 * Only millisecs are same as it is the oly member variable saved and retrieved.
 * @author nishantagrawal
 *
 */
public class CustomSerializationWithoutExternalizable implements Serializable {

	private Calendar date = new GregorianCalendar().getInstance();
	

	private void writeObject(ObjectOutputStream oos) throws IOException {

		oos.defaultWriteObject();
		oos.writeInt(date.get(Calendar.MILLISECOND));

	}

	private void readObject(ObjectInputStream ois)
			throws ClassNotFoundException, IOException {
		// default deserialization
		ois.defaultReadObject();
		date = new GregorianCalendar().getInstance();
		date.set(Calendar.MILLISECOND, ois.readInt());

	}
	
	
	@Override
	public String toString() {
		// TODO Auto-generated method stub
		return date.toString();
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println("Start Writing!");
		
		CustomSerializationWithoutExternalizable obj = new CustomSerializationWithoutExternalizable();
		ObjectOutputStream oos;
		try {
			oos = new ObjectOutputStream(
					new FileOutputStream("/udev/CustomSerializationWithoutExternalizable.ser"));
			System.out.println("Object being written is: " + obj);
			oos.writeObject(obj);
			oos.flush();
			oos.close();
			
			Thread.sleep(2000);
			
			System.out.println("Start Reading!");
			ObjectInputStream ois = new ObjectInputStream(new FileInputStream(
					"/udev/CustomSerializationWithoutExternalizable.ser"));
			CustomSerializationWithoutExternalizable simpleObject = (CustomSerializationWithoutExternalizable) ois.readObject();
			ois.close();
			
			System.out.println("Object read is: " + simpleObject);

			System.out.println("Reading complete.");
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		System.out.println("Writing complete.");

	}

}
